package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"time"
	"zc1/model/mysql"
	redis "zc1/model/reids"
	"zc1/zcrpc/internal/svc"
	"zc1/zcrpc/zcrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ZcListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewZcListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ZcListLogic {
	return &ZcListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ZcListLogic) ZcList(in *zcrpc.ZcListRequest) (*zcrpc.ZcListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	size := in.Size
	if page <= 0 {
		page = 1
	}
	switch {
	case size > 100:
		size = 100
	case size <= 100:
		size = 5
	}
	offset := (page - 1) * size
	var product []mysql.Product
	itoa := strconv.Itoa(int(offset))
	get := redis.Client.Get("proList" + itoa)
	if get.Val() == "" {
		mysql.DB.Debug().Where("user_id =?", in.Userid).Offset(int(offset)).Limit(int(size)).Order("price desc").Find(&product)
		marshal, _ := json.Marshal(product)
		redis.Client.Set("proList"+itoa, marshal, time.Hour*24)
		fmt.Println("这是mysql")
	} else {
		json.Unmarshal([]byte(get.Val()), &product)
		fmt.Println("这是redis")
	}

	var productList []*zcrpc.ZcList
	for _, m := range product {
		list := zcrpc.ZcList{
			Userid: int64(m.Money),
			Name:   m.Name,
			Number: m.Number,
			Price:  float32(m.Price),
			Money:  float32(m.Money),
			Image:  m.Image,
		}
		productList = append(productList, &list)
	}

	return &zcrpc.ZcListResponse{List: productList}, nil
}
